#include "IndexVisualizer.h"

struct myExtraLongInt;

void IndexVisualizer::addToStringMethod(string (*keyToString) (char*))
{
    this->keyToString = keyToString;
}

void IndexVisualizer::addNode(string nodeDescription)
{
    nodes.push_back(nodeDescription);
}

void IndexVisualizer::addChildRelation(unsigned from, unsigned position, unsigned to)
{
    relations.push_back("node" + toString(from) + ":ptr" + toString(position) + " -> node" + toString(to) + ":count;");
}

void IndexVisualizer::addNextRelation(unsigned from, unsigned to)
{
    relations.push_back("node" + toString(from) + ":next -> node" + toString(to) + ":count;");
}

void IndexVisualizer::print()
{
    cout << "digraph IndexBTree {" << endl;
    for(vector<string>::iterator it = nodes.begin(); it != nodes.end(); it++)
    {
        cout << *it << endl;
    }

    for(vector<string>::iterator it = relations.begin(); it != relations.end(); it++)
    {
        cout << *it << endl;
    }
    cout << "}" << endl;
}

void IndexVisualizer::saveAs(string fileName)
{
	string tmpFile = "./images/tmpOut" + fileName + ".dot";
    FILE* file = fopen(tmpFile.c_str(), "w");
    if (file == NULL)
    {
        cout << "Visualizer: Something bad happened: error while opening file." << endl;
        exit(1);
    }
    if (fseek(file, 0, SEEK_SET) != 0)
    {
        cout << "Visualizer: Something bad happened: error while seeking file." << endl;
        exit(1);
    }

    string data = "digraph IndexBTree {\n";
    for(vector<string>::iterator it = nodes.begin(); it != nodes.end(); it++)
        data += std::move(*it) + std::move("\n");

    for(vector<string>::iterator it = relations.begin(); it != relations.end(); it++)
        data += std::move(*it) + std::move("\n");

    data += std::move("}");

    const char* x = data.c_str();
    unsigned length = data.length();

    if (fwrite(x, sizeof(char), length, file) != length)
    {
        cout << "Visualizer: Something bad happened: error while writing file." << endl;
        exit(1);
    }

    fflush(file);
    fclose(file);

	string command = "dot -Tpng ./images/tmpOut" + fileName + ".dot -o ./images/" + fileName;

	popen(command.c_str(), "r");
	usleep(1000 * 8000);
}

string IndexVisualizer::toString(unsigned u)
{
    ostringstream s;
    s << u;
    return s.str();
}

string IndexVisualizer::toString(TID& t)
{
    ostringstream s1, s2;
    s1 << t.pageId;
    s2 << t.slotId;
    return s1.str() + ":" + s2.str();
}

string IndexVisualizer::toString(char* x)
{
    return "TODO";
}
